import os
import functools
import logging

from google.appengine.api import users
from google.appengine.ext.webapp import template

TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'templates')

def templated(filename):
    def wrap_fun(f):
        @functools.wraps(f)
        def wrapped(self, *args, **kwargs):
            # Populate the template vars with a few useful tidbits
            self.user = users.get_current_user()
            if self.user:
                account_url = users.create_logout_url(self.request.uri)
            else:
                account_url = users.create_login_url(self.request.uri)

            template_vars = {
                'user': self.user,
                'account_url': account_url,
                }

            # Now, invoke the wrapped handler and possibly output a
            # template.
            func_template_vars = f(self, *args, **kwargs)
            if func_template_vars is not None:
                template_vars.update(func_template_vars)
                self.response.out.write(template.render(
                    os.path.join(TEMPLATE_DIR, filename), template_vars))
        return wrapped
    return wrap_fun

def admin_only(f):
    @functools.wraps(f)
    def wrap_fun(self, *args, **kwargs):
        if users.is_current_user_admin():
            return f(self, *args, **kwargs)
        else:
            self.error(404)
    return wrap_fun
